package sf.database.meta;

import sf.tools.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MetaHolderExtend {
    // 动态表元数据池
    protected static final Map<String, TableMapping> dynPool = new ConcurrentHashMap<>(8);
    // 反向查找表
    protected static final Map<String, TableMapping> inverseMapping = new ConcurrentHashMap<>();

    /**
     * 逆向查找元模型
     * @param schema
     * @param table
     */
    public static TableMapping lookup(String schema, String table) {
        String key = (schema + "." + table).toUpperCase();
        TableMapping m = inverseMapping.get(key);
        if (m != null)
            return m;

        // Lookup static models
        for (TableMapping meta : MetaHolder.pool.values()) {
            String tablename = meta.getTableName();
            if (schema != null && (!StringUtils.equals(meta.getSchema(), schema))) {// schema不同则跳
                continue;
            }
            if (tablename.equalsIgnoreCase(table)) {
                m = meta;
                break;
            }
        }
        if (m == null) {
            // Lookup dynamic models
            for (TableMapping meta : dynPool.values()) {
                String tablename = meta.getTableName();
                if (schema != null && (!StringUtils.equals(meta.getSchema(), schema))) {// schema不同则跳过
                    continue;
                }
                if (tablename.equalsIgnoreCase(table)) {
                    m = meta;
                    break;
                }
            }
        }
        inverseMapping.put(key, m);
        return m;
    }

    public static void clear() {
        dynPool.clear();
        inverseMapping.clear();
    }
}
